/*
 * @Author: C.
 * @Date: 2023-02-28 16:52:36
 */
import { ref, watchEffect, unref, computed, reactive } from 'vue';
import { number2String, smalltoBIG } from './utils';
import { onKeyDown } from '@vueuse/core';
export function useSummary({ List }) {
  const leftValue = ref(0);
  const rightValue = ref(0);
  const total = computed(() => {
    if (unref(leftValue) === unref(rightValue) && unref(leftValue) !== 0) {
      return smalltoBIG(unref(leftValue));
    } else {
      return '零元整';
    }
  });
  watchEffect(() => {
    let left = 0,
      right = 0;
    unref(List).forEach((item) => {
      // console.log(item.debit.value);
      left += item.debit.value;
      right += item.creditor.value;
    });
    leftValue.value = left;
    rightValue.value = right;
  });
  const leftAmount = computed(() => {
    return number2String(unref(leftValue));
  });
  const rightAmount = computed(() => {
    return number2String(unref(rightValue));
  });
  return {
    leftValue,
    rightValue,
    leftAmount,
    rightAmount,
    total,
  };
}

export function usekeyboard({ List }) {
  const currentCell = reactive<{
    level: null | number;
    cell: any;
  }>({
    level: null,
    cell: null,
  });
  function handleClickOutside() {
    if (currentCell.cell === null) return;
    currentCell.cell.inputShow = false;
    currentCell.cell = null;
    currentCell.level = null;
  }
  function cellFoucs(cellObj, level) {
    if (currentCell.cell) {
      currentCell.cell.inputShow = false;
    }
    currentCell.level = level;
    currentCell.cell = cellObj;
    currentCell.cell.inputShow = true;
  }
  function cellBlur(row, type) {
    if (!['debit', 'creditor'].includes(type)) return;
    if (row[type].value.toFixed().toString().length > 11) {
      row[type].value = 0;
    }
    if (!row[type].value) return;
    switch (type) {
      case 'debit':
        row.creditor.value = 0;
        break;
      case 'creditor':
        row.debit.value = 0;
        break;
      default:
        break;
    }
  }
  onKeyDown(['Enter', 'Tab', 'ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'], (e) => {
    e.preventDefault();
    if (currentCell.cell === null) return;
    let handleFunc;
    if (['Enter', 'Tab', 'ArrowRight'].includes(e.code)) {
      handleFunc = currentCell.cell.getNextCell;
    }
    switch (e.code) {
      case 'ArrowLeft':
        handleFunc = currentCell.cell.getRightCell;
        break;
      case 'ArrowDown':
        handleFunc = currentCell.cell.getDownCell;
        break;
      case 'ArrowUp':
        handleFunc = currentCell.cell.getUpCell;
        break;
      default:
        break;
    }
    const { cellObj, level } = handleFunc(List, currentCell);
    cellFoucs(cellObj, level);
  });
  return {
    handleClickOutside,
    cellFoucs,
    cellBlur,
  };
}
